<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\api\controller;

use think\facade\Db;
use app\common\service\Post as PostService;
use app\common\service\BaseService;
use app\common\service\Message;
use app\common\model\Post as PostModel;
use app\common\service\Wechat;
use app\common\model\VoteResult;
use app\common\model\Discuss as DiscussModel;

class Post extends ApiBase
{

    //获取帖子列表
    public function list()
    {
        $discussTitle = input("discuss_title");
        $topicId = input("topic_id");
        $classId = input("class_id");

        $uid = input("user_id");
        $type = input("type");

        $postKeyword = input("post_keyword");
        $userKeyword = input("user_keyword");
        $topicKeyword = input("topic_keyword");

        $where = [];

        if ($classId) {
            $where[] = ["post.class_id", "=", $classId];
        }

        if ($type) {
            $where[] = ["post.type", "=", $type];
        }

        if ($discussTitle) {
            $where[] = ["discuss_list", "like", "%" . $discussTitle . "%"];
        }

        if ($topicId) {
            $where[] = ["topic_id", "=", $topicId];
        }

        if ($uid) {
            $where[] = ["post.user_id", "=", $uid];
        }

        if ($postKeyword) {
            $where[] = ["content", "like", "%" . $postKeyword . "%"];
        }

        if ($userKeyword) {
            $wUser[] = ["username", "like", "%" . $userKeyword . "%"];
            $uids = Db::name("user")->where($wUser)->column("id");
            $where[] = ["post.user_id", "in", $uids];
        }

        if ($topicKeyword) {
            $wTopic[] = ["topic_name", "like", "%" . $topicKeyword . "%"];
            $topic_ids = Db::name("topic")->where($wTopic)->column("id");
            $where[] = ["topic_id", "in", $topic_ids];
        }

        $list = PostModel::getList($where);
        return message($list);
    }

    //关注用户的帖子列表
    public function followUserPost()
    {
        $loginUserId = BaseService::getLoginUserIdNoAuth();

        $userIds = Db::name("follow")->where("user_id", $loginUserId)->column("follow_uid");

        $list = PostService::getPostListByUserId($userIds);
        return message($list);
    }

    //搜索帖子
    public function search()
    {
        $keyword = input("keyword");
        $where[] = ["content", "like", "%$keyword%"];
        $list = PostModel::getList($where);
        return message($list);
    }

    //发布帖子
    public function release()
    {

        $userId = BaseService::getLoginUserId();
        $user = Db::name("user")->find($userId);

        if ($user["status"] != 0) {
            return error("该用户已被禁用");
        }

        $type = input("type");
        $media = input("media");

        //如果为视频类型帖子时检测是否上传视频
        if ($type == 2 && count($media) == 0) {
            return error("请上传视频");
        }

        $data = input("post.");
        $data["id"] = BaseService::randomStr();
        $data["user_id"] = $userId;
        $data["class_id"] = Db::name("topic")->where("id", $data["topic_id"])->value("class_id");
        $data["create_time"] = time();

        $data["discuss_list"] = json_encode($data["discuss_list"],JSON_UNESCAPED_UNICODE);

        //微信小程序用户检测内容安全
        if ($user["type"] == 1) {
            $wechat = new Wechat();

            if ($data["content"] && !$wechat->checkText($data["content"], $user["openid"])) {
                return error("内容违规违法");
            }
        }

        $post = PostModel::create($data);
        if ($post->id) {

            Db::name('user')->where('id', $userId)->inc('post_num')->update();
            Db::name('user')->where('id', $userId)->inc('exp', 5)->update();
            Db::name('user')->where('id', $userId)->inc('integral', 5)->update();
            Db::name('topic')->where('id', $data["topic_id"])->inc('post_num')->update();

            return message(["id" => $post->id], "发布成功");
        }

        return error("发布失败");
    }

    /**
     * [帖子详情]
     * @return [json]
     */
    public function detail()
    {

        $id = input("id");
        $userId = BaseService::getLoginUserIdNoAuth();

        Db::name('post')->where('id', $id)->inc('see_num')->update();
        $postInfo = PostModel::withJoin(["userInfo"])->find($id);


        $topicId = $postInfo["topic_id"];

        if ($topicId) {
            $postInfo["topic_info"] = \app\common\model\Topic::find($topicId);
        }

        //是否已关注帖子作者
        $postInfo["is_follow"] = false;
        $isFollow = Db::name("follow")->where(["user_id" => $userId, "follow_uid" => $postInfo["user_id"]])->find();
        if ($isFollow) {
            $postInfo["is_follow"] = true;
        }

        $postInfo["comment_count"] = Db::name("comment")->where("post_id", $id)->count();

        //是否已点赞帖子
        $postInfo["is_thumb"] = false;
        $isThumb = Db::name("post_thumb")->where(["user_id" => $userId, "post_id" => $id])->find();
        if ($isThumb) {
            $postInfo["is_thumb"] = true;
        }

        //投票
        if ($postInfo["vote_id"]) {
            $vote = Db::name("vote_subject")->where("id", $postInfo["vote_id"])->find();
            $vote["options"] = Db::name("vote_option")->where("vote_id", $vote["id"])->select();
            $postInfo["vote_info"] = $vote;
            //投票结果
            $voteResult = VoteResult::where(["vote_id" => $postInfo["vote_id"], "user_id" => $userId])->find();

            $postInfo["is_vote_result"] = false;
            if ($voteResult) {
                $postInfo["is_vote_result"] = true;
            }

        }

        $postInfo["discuss_list"] = json_decode($postInfo["discuss_list"]);
        return message($postInfo);
    }

    //发布的帖子
    public function releaseList()
    {
        $uid = BaseService::getLoginUserId();
        $where["post.user_id"] = $uid;

        $list = PostModel::getList($where);
        return message($list);
    }

    //删除帖子
    public function del()
    {
        $id = input("id");
        $res = PostModel::destroy($id);
        if ($res) {
            $topicId = Db::name("post")->where("id", $id)->value("topic_id");
            Db::name('topic')->where('id', $topicId)->dec('post_num')->update();
            return message("删除成功");
        }
        return error("删除失败");
    }

    //用户点赞的帖子
    public function thumbList()
    {
        $userId = BaseService::getLoginUserId();
        $postIds = Db::name("post_thumb")->where("user_id", $userId)->column("post_id");

        $where[] = ["post.id", "in", $postIds];
        $list = PostModel::getList($where);
        return message($list);
    }

    public function checkPostImg()
    {
        $userId = BaseService::getLoginUserId();
        $user = Db::name("user")->find($userId);

        $postId = input("post_id");

        $imgList = Db::name("post")->where("id", $postId)->value("media");
        $imgList = json_decode($imgList);

        $wechat = new Wechat();

        $checkRes = false;
        foreach ($imgList as $key => $imgSrc) {
            $checkRes = $wechat->mediaCheck($imgSrc, $user["openid"]);
            if (!$checkRes) {
                $imgList[$key] = '';
                $checkRes = true;
            }
        }

        if ($checkRes) {
            PostModel::where("id", $postId)->update(["media" => $imgList]);
        }

        return message(["check_res" => "success"]);
    }

    //点赞帖子
    public function thumbAdd()
    {
        $userId = BaseService::getLoginUserId();
        $postId = input("id");
        $toUserId = input("user_id");

        $data["id"] = BaseService::randomStr();
        $data["user_id"] = $userId;
        $data["post_id"] = $postId;

        $isCollection = Db::name("post_thumb")->where($data)->find();
        if ($isCollection) {
            return error("请勿重复点赞");
        }

        $res = Db::name("post_thumb")->insert($data);

        if ($res) {
            Db::name("post")->where("id", $postId)->inc('thumb_num')->update();
            Message::send($userId, $toUserId, $postId, 3, "点赞了您的贴子");

            return message("点赞成功");
        }
        return error("点赞失败");
    }

    //取消点赞
    public function thumbCancel()
    {
        $userId = BaseService::getLoginUserId();
        $postId = input("id");
        $where["user_id"] = $userId;
        $where["post_id"] = $postId;
        $res = Db::name("post_thumb")->where($where)->delete();

        if ($res) {
            Db::name("post")->where("id", $postId)->dec('thumb_num')->update();
            return message("已取消点赞");
        }
        return error("取消点赞失败");
    }

    //发布投票
    public function voteAdd()
    {
        $data["user_id"] = BaseService::getLoginUserId();

        $data["id"] = BaseService::randomStr();
        $data["topic_id"] = input("topic_id");
        $data["content"] = input("content");
        $data["address"] = input("address");
        $data["type"] = 4;

        $voteId = BaseService::randomStr();
        $voteSubjectData["id"] = $voteId;
        $voteSubjectData["title"] = input("vote_title");
        $voteSubjectData["type"] = input("vote_type");
        $voteSubjectData["create_time"] = time();

        $expireTimeNum = input("expire_time");
        if ($expireTimeNum === 1) {
            $voteSubjectData["expire_time"] = time() + 86400;
        }

        if ($expireTimeNum === 2) {
            $voteSubjectData["expire_time"] = time() + 86400 * 7;
        }

        if ($expireTimeNum === 3) {
            $voteSubjectData["expire_time"] = time() + 86400 * 30;
        }

        if ($expireTimeNum === 4) {
            $voteSubjectData["expire_time"] = time() + 86400 * 90;
        }

        $voteSubject = Db::name("vote_subject")->insert($voteSubjectData);

        if ($voteSubject) {
            $voteOptionData["vote_id"] = $voteId;
            $voteOptions = input("vote_options");

            foreach ($voteOptions as $item) {
                $voteOptionData["id"] = BaseService::randomStr();
                $voteOptionData["content"] = $item["value"];
                Db::name("vote_option")->insert($voteOptionData);
            }

            $data["vote_id"] = $voteId;
            $postAdd = PostModel::create($data);
        }

        return message(["id" => $postAdd->id], "发布成功");
    }

    //当前登录用户加入圈子的动态列表
    public function postListByjoinTopic()
    {
        $userId = BaseService::getLoginUserIdNoAuth();
        $topicIds = Db::name("user_topic")->where("user_id", $userId)->column("topic_id");

        $where[] = ['topic_id', 'in', $topicIds];
        $postList = PostModel::getList($where);

        return message($postList);
    }
}